package com.kai.auth.handler;

import com.kai.auth.enums.AuthErrorCodeConstants;
import com.kai.common.data.Result;
import com.kai.common.util.IpAddressUtil;
import com.kai.common.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 未认证处理器
 * </p>
 *
 * @author weijk
 * @since 2023/7/19
 */
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        String ip = IpAddressUtil.get(httpServletRequest);
        log.error("未登录, url=[{}], ip=[{}], msg=[{}]", httpServletRequest.getRequestURI(), ip, e.getMessage(), e);

        WebUtil.writeJson(Result.fail(AuthErrorCodeConstants.NO_LOGIN), httpServletResponse);
    }
}
